<!-- eslint-disable prettier/prettier -->
<!-- eslint-disable vue/valid-attribute-name -->
<template>
  <div>
    <category :scene="scene" />
    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table border style="margin: 10px 0px" :data="attr">
          <el-table-column
            label="序号"
            type="index"
            :align="'center'"
            width="85px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                v-for="item of row.attrValueList"
                type="primary"
                default="row.attrName"
                :key="item.id"
                style="margin: 5px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row, $index }">
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm :title="`你确定要删除${row.attrName}?`" width="200px" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名称"
              v-model="attrParams.attrName"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button size="default" type="error" @click="cancelAttr">
          取消
        </el-button>
        <el-table
          border
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="85px"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index}">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                v-if="row.flag"
                size="small"
                @blur="toLook(row, $index)"
                placeholder="请输入属性值名称"
                v-model="row.valueName"
              />
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="deleteAttrValue($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="saveAttr"
        >
          保存
        </el-button>
        <el-button size="default" @click="cancelAttr">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
//组合式API函数watch
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue"
//映入获取已有属性与属性值接口
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "../../../api/product/attr/index"
import useCategoryStore from "../../../store/modules/category"
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from "../../../api/product/attr/type"
import { ElMessage, ElNotification } from "element-plus"
let categoryStore = useCategoryStore()

//存储已有的属性与属性值
let attr = ref<Attr[]>([])

let scene = ref<number>(0)

let inputArr = ref<[]>([])

//收集新增的数据
let attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
})

//监听仓库三级分类id
watch(
  () => categoryStore.c3Id,
  () => {
    attr.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)

const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  if (c3Id) {
    let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
    if (result.code == 200) {
      attr.value = result.data
    }
  }
}

const addAttr = () => {
  //清空数据
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    //收集三级分类id
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  })
  scene.value = 1
}

const updateAttr = (row: Attr) => {
  scene.value = 1
  //将已有的属性对象赋值给params对象
  //ES6对象绑定
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const cancelAttr = () => {
  scene.value = 0
}

const saveAttr = async () => {
  //收集参数 请求

  try {
    let result: any = await reqAddOrUpdateAttr(attrParams)
    if (result.code == 200) {
      //提示信息
      ElNotification({
        type: "success",
        message: attrParams.id ? "修改成功" : "添加成功",
      })
      scene.value = 0
      getAttr()
    }
  } catch (error) {
    ElNotification({ type: "error", message: (error as Error).message })
  }
}

const addAttrValue = () => {
  //点击添加属性按钮后，像数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: "",
    flag: true, //控制每个属性值编辑模式与查看模式切换
  })

  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

const toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() == "") {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({ type: "error", message: "属性值不为空" })
    return
  }
  let repeat = attrParams.attrValueList.find((item) => {
    //当前失去焦点属性对象从当前数组去除
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({ type: "error", message: "属性值不能重复" })
    return
  }
  //响应的属性值flag
  row.flag = false
}

const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

const deleteAttrValue = ($index: number) => {
  attrParams.attrValueList.splice($index, 1)
}

const deleteAttr = async (id: number) => {
  let result = await reqDeleteAttr(id)
  if (result.code == 200) {
    ElMessage({ type: "success", message: "删除成功" })
    //重新获取数据
    getAttr()
  } else {
    ElMessage({ type: "error", message: "删除失败" })
  }
}

//路由组件销毁的时候，吧仓库分类相关的数据清空
onBeforeUnmount(() => {
  //清空分类仓库
  categoryStore.$reset()
})
</script>

<style scoped></style>
